package com.atguigu.gmall.realtime.utils;


import com.atguigu.gmall.realtime.bean.TableProcess;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: JDBCUtil
 * Package: com.atguigu.gmall.realtime.utils
 * Description:
 *
 *             select * from t;                                 多行多列
 *             select count(*) from t;                          单行单列
 *             select count(*) from t group by dept_name;       单行多列
 *             select * from t where id = 'xxx'; id为主键        多行单列
 * @Author ChenJun(有志男青年)
 * @Create 2023/4/27 11:34
 * @Version 1.0
 */
public class JDBCUtil {

    //泛型方法
    public static <T> List<T> queryList(Connection connection,String sql,Class<T> clz,boolean underScoreToCamel) throws Exception {

        // 创建集合用于存放结果
        ArrayList<T> list = new ArrayList<>();

        // 预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 执行查询操作
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 遍历resultSet,将每行数据封装为T对象
        while(resultSet.next()){

            // 创建t对象
            T t = clz.newInstance();

            //列遍历,将每个列设置进T对象
            for (int i = 1; i < columnCount + 1; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                if (underScoreToCamel){
                    columnName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName.toLowerCase());
                }

                //将列名与列值放入T对象
                BeanUtils.setProperty(t,columnName,value);
            }

            list.add(t);
        }

        //释放资源
        resultSet.close();
        preparedStatement.close();

        //返回集合
        return list;
    }


    //测试jdbc
    public static void main(String[] args) throws Exception {

//        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();

        Connection connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall_config?" +
                "user=root&password=000000&useUnicode=true&" +
                "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");

        List<TableProcess> queryList = queryList(connection, "select * from table_process", TableProcess.class, true);

        for (TableProcess jsonObject : queryList) {
            System.out.println(jsonObject);
        }

        connection.close();
    }

}
